package net.labdemo.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import net.labdemo.entity.User;
import net.labdemo.service.UserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		User entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = userService.get(Long.valueOf(id));
		}
		if (entity == null){
			entity = new User();
		}
		return entity;
	}
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String save(User u,@RequestParam String mail,@RequestParam String inpswd){
		System.out.println("[CP]:"+u);
		
		u.setMail(mail);
		u.setInpswd(inpswd);
		System.out.println("[C]mail:"+mail+",inpswd:"+inpswd);
		if(userService.register(u)>0){
			return "redirect:/user/login";
		}
		return "user/form";
	}
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String form(User u,Model model){
		model.addAttribute("user", u);
		return "user/form";
	}
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String get(User u,Model model){
		model.addAttribute("user", u);
		return "user/get";
	}
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String query(@ModelAttribute("user") User formUser,Model model){
		System.out.println("[CF]:"+formUser);
		
		User u=userService.login(formUser.getMail(), formUser.getInpswd());
		if(u!=null){
			return "redirect:/article";
		}
		return "user/get";
	}
}
